import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:study_demo/db/isar.dart';

import '../../util/utils.dart';

class RelaxController extends BaseController with LocalDataRelaxInfo {
  final relaxInfoList = <RelaxInfo>[].obs;

  onInit() async {
    super.onInit();
    await queryRelaxInfo();
    relaxInfoList.assignAll(relaxs);
  }

  addRecord() {
    selectTime();
  }

  selectTime() async {
    var dateTime = await showDatePicker(
      context: Get.overlayContext!,
      initialDate: DateTime.now(),
      firstDate: DateTime(1970),
      lastDate: DateTime.now(),
    );
    if (dateTime != null) {
      print('datetime:$dateTime');
      RelaxInfo relaxInfo = RelaxInfo();
      String date = formatDate(dateTime);
      if (await relaxs.isExist(date)) {
        toast('当前日期已存在,请重新选择');
        return;
      }
      relaxInfo.id = DateTime.now().millisecondsSinceEpoch;
      relaxInfo.date = date;
      print('date:${relaxInfo.date}');
      relaxInfo.count = 0;
      relaxs.save(relaxInfo);
      relaxInfoList.add(relaxInfo);
      relaxInfoList.sort((a, b) => b.date.compareTo(a.date)); //从小到大
    }
  }

  updateRecord(RelaxInfo relaxInfo, {bool isAdd = true}) {
    if (isAdd) {
      relaxInfo.count++;
    } else {
      relaxInfo.count--;
    }
    relaxs.save(relaxInfo);
    relaxInfoList.refresh();
  }

  finish(RelaxInfo relaxInfo) {
    relaxs.save(relaxInfo);
    relaxInfoList.refresh();
  }

  deleteRecord(String date) {
    relaxs.delete(date);
    relaxInfoList.removeWhere((it) => it.date == date);
    relaxInfoList.refresh();
  }
}
